package cn.ljlao.mall.product.goods.exception;

import cn.ljlao.common.exception.MallResponseCode;
import cn.ljlao.common.utils.R;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice(basePackages = "cn.ljlao.mall.product.goods.controller")
public class MallExceptionHandler {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R getMethodArgumentNotValidException(MethodArgumentNotValidException e){
        //获取报错结果集
        BindingResult bindingResult = e.getBindingResult();
        //封装返回的集合
        Map<String,String> map = new HashMap<>();
        //便利结果集
        bindingResult.getFieldErrors().forEach((fieldError -> {
            //字段名 为key  错误消息为 value
            map.put(fieldError.getField(),fieldError.getDefaultMessage());
        }));
        //弹出去
        return R.error(MallResponseCode.DATA_TRANSFER_ERR).put("data",map);
    }
}
